package org.mch.func.m_px.sorteg.handle;

import java.awt.Color;
import java.awt.Font;
import java.awt.Point;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

import org.apache.commons.lang3.RandomUtils;
import org.mch.func.m_px.sorteg.SortPanel;
import org.mch.swingm.core.MToggleButton;
import org.mch.swingm.core.MToggleButtonGroup;

public class HandleCreateNewBtnArry extends AbstractLCSXEGHandle {

	public HandleCreateNewBtnArry(SortPanel panel) {
		super(panel);
	}

	public void onHandle(JButton btn) {
		DlgCreateNewBtnArry dcnba = new DlgCreateNewBtnArry();
		Point p = new Point(btn.getX(), btn.getY());
		SwingUtilities.convertPointToScreen(p, btn);// 将一个点从组件的坐标系统转换到屏幕坐标
		dcnba.setBounds(((int) p.getX()) + btn.getWidth(), ((int) p.getY()) - 137, 253, 137);
		dcnba.setVisible(true);
		int[] values = dcnba.getValues();
		if (values == null) {
			return;
		}

		getPanel().getPanelUp().removeAll();
		getPanel().getPanelUp().add(getPanel().getLabelUp());
		getPanel().getPanelUp().add(getPanel().getLabelDown());

		// 生成按钮数字
		int[] numbers = new int[values[2]];
		for (int i = 0; i < numbers.length; i++) {
			numbers[i] = RandomUtils.nextInt(values[0], values[1]);
		}

		MToggleButtonGroup tBtnGroup = new MToggleButtonGroup(2);

		// 根据生成的数字，生成按钮；
		MToggleButton[] btns = new MToggleButton[numbers.length];
		for (int i = 0; i < btns.length; i++) {
			btns[i] = new MToggleButton(numbers[i] + "");
			btns[i].setUserObj(numbers[i]);
			btns[i].setFont(new Font("Dialog", Font.PLAIN, 20));
			int width = 75;
			int height = 25;
			int x = 10 + (width * i) + 25 * i;
			int y = 50;
			btns[i].setBounds(x, y, width, height);
			getPanel().getPanelUp().add(btns[i]);
			getPanel().getPanelUp().add(createIndexLabel(x, y, width, height, i));

			tBtnGroup.addGroupButton(btns[i]);
		}

		getPanel().setBtnSorts(btns);

		getPanel().getPanelUp().updateUI();
	}

	/**
	 * 创建一个索引 JLabel；
	 * 
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 * @param index
	 * @return
	 */
	private JLabel createIndexLabel(int x, int y, int width, int height, int index) {
		JLabel label = new JLabel("" + index);
		label.setBounds(x, y - 30, width, height);
		label.setFont(new Font("宋体", Font.BOLD, 15));
		label.setHorizontalTextPosition(SwingConstants.CENTER);
		label.setHorizontalAlignment(SwingConstants.CENTER);
		label.setBorder(new LineBorder(Color.BLUE));
		return label;
	}
}
